package com.partner.action.member;

import java.io.IOException;
import java.text.ParseException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.partner.bean.sysright.TSysrole;
import com.partner.bean.sysright.TSysuserVo;
import com.partner.frame.common.GetProPertiesUtil;
import com.partner.service.sysright.SysRoleManagerService;
import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.partner.bean.member.Member;
import com.partner.bean.member.MemberVo;
import com.partner.bean.order.Order;
import com.partner.bean.order.Ordermi;
import com.partner.bean.product.Product;
import com.partner.bean.sysright.TSysuser;
import com.partner.frame.common.CommonInstans;
import com.partner.service.member.MemberService;
import com.partner.service.order.OrderService;
import com.partner.service.order.OrdermiService;
import com.partner.service.product.ProductService;
import com.partner.service.sysright.SysManagerService;
import com.partner.service.withdraw.WithdrawService;
import com.partner.frame.Result;
import com.partner.frame.common.ConstantsMark;
import com.partner.frame.support.util.TujiPassWordEncoder;
import com.partner.frame.util.MemberUtil;

@Controller
@RequestMapping("/member")
public class MemberAction {
	
	@Autowired
	private MemberService memberService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private OrdermiService ordermiService;
	@Autowired
	private SysManagerService sysManagerService;
	@Autowired
	private ProductService productService;
	@Autowired
	private WithdrawService withdrawService;
	@Autowired
	private SysRoleManagerService sysRoleManagerService;
	
	@RequestMapping(value = "/list")
	public ModelAndView list(HttpServletRequest request,Member member
			) throws ParseException{
		ModelAndView result = new ModelAndView();
		String sysusername = (String)request.getSession().getAttribute(CommonInstans.SYSUSERNAME);
		int sysuserid = (int)request.getSession().getAttribute(CommonInstans.LOGINUSERID);
		if(!sysusername.equals("admin")){
			member.setSysuserid(sysuserid);
		}

		Integer adminRoleId = getAdminRoleId();
		if(adminRoleId != null){
			TSysuser tSysuser = new TSysuser();
			tSysuser.setUsername(sysusername);
			//根据登录名查询出登录用户
			TSysuserVo sysUser = sysManagerService.getSysUserbyUsername(tSysuser);
			if(sysUser != null ){
				if(adminRoleId.equals(sysUser.getRoleid())){
					member.setSysuserid(null);
				}
			}
		}

		List<Member> memberList = memberService.selectAll(member);
		
		result.addObject("member", member);
		result.addObject("memberList", memberList);
		result.setViewName("/pages/member/list");
		return result;
	}

	private Integer getAdminRoleId() {
		//查找是否有管理员角色
		String adminRoleName = "管理员";
		try {
			adminRoleName = GetProPertiesUtil.getProperties("system.properties","admin.rolename");
		} catch (Exception e) {
		}
		List<TSysrole> roles = sysRoleManagerService.getAllRoles();
		for(TSysrole role : roles){
			if(adminRoleName.equals(role.getRolename())){
				return  role.getId();
			}
		}
		return null;
	}

	@RequestMapping(value = "/before",method = RequestMethod.GET)
	public ModelAndView before(HttpServletRequest request,HttpServletResponse response,Integer id){

		ModelAndView result = new ModelAndView();
		Member data = new Member();
		if(id!=0){
			data = memberService.selectByPrimaryId(id);
		}
		result.addObject("data", data);
		result.setViewName("/pages/member/edit");
		return result;
	}
	
	@RequestMapping(value = "/updateMember",method = RequestMethod.POST)
	@ResponseBody
	public Result updateMember(HttpServletRequest request,Member member) throws ParseException{
		Result result = new Result();
		int sysuserid = (int)request.getSession().getAttribute(CommonInstans.LOGINUSERID);
		//id == 0 进入新增
		if(member.getId()==0){
			Member m1 = new Member();
			m1.setTel(member.getTel());
			List<Member> members = memberService.selectAll(m1);
			if(members.size()==0){
				member.setSysuserid(sysuserid);
				if(member.getNum()!=null && member.getNum()!=0){
					Member m = memberService.selectByNum(member.getNum());
					if(m!=null){
						member.setPname(m.getName());
						member.setPtel(m.getTel());
						member.setPid(m.getId());
					}
				}
				member.setStatus(1);
				member.setDisabled(0);
				member.setSonnum(0);
				member.setLevel(1);//默认第一级，天使合伙人
				member.setMembernum(0);
				member.setSaleamount(0);
				member.setWithdrawintegral(0);
				member.setNum(MemberUtil.getMaxNum(memberService)+1);
				Integer id = memberService.insert(member);
				MemberUtil.addAccountOrder(id,memberService,ordermiService,sysManagerService);
//				MemberUtil.setMembernum(id,memberService);
				result.setDesc(ConstantsMark.INFO_SAVESUCCESS);
			}else{
				result.setDesc("号码"+member.getTel()+"已注册！");
			}
		}else{
			//进入修改
			memberService.updateByPrimaryKey(member);
			result.setDesc(ConstantsMark.INFO_UPDATESUCCESS);
		}
		return result;
	}
	
	@RequestMapping(value = "/frozenAccount",method = RequestMethod.POST)
	@ResponseBody
	public Result frozenAccount(HttpServletRequest request,HttpServletResponse response,Integer id,Integer status)throws ParseException{
		Result result = new Result();
		Member data = memberService.selectByPrimaryId(id);
		data.setStatus(status);
		TSysuser bean = new TSysuser();
		bean.setUsername(data.getTel());
		TSysuser user = sysManagerService.getSysUserbyUsername(bean);
		if(user!=null && status==1){
			user.setIsuse("y");
		}else if(user!=null && status==0){
			user.setIsuse("n");
		}
		sysManagerService.updateByPrimaryKey(user);
		memberService.updateByPrimaryKey(data);
		result.setDesc(ConstantsMark.INFO_UPDATESUCCESS);
		return result;
	}
	
	@RequestMapping(value = "/resetPassword",method = RequestMethod.POST)
	@ResponseBody
	public Result resetPassword(HttpServletRequest request,HttpServletResponse response,Integer id){
		Result result = new Result();
		Member data = memberService.selectByPrimaryId(id);
		TSysuser bean = new TSysuser();
		bean.setUsername(data.getTel());
		TSysuser user = sysManagerService.getSysUserbyUsername(bean);
		if(user!=null){
			user.setPassword(TujiPassWordEncoder.MD5("123456"));
			sysManagerService.updateByPrimaryKey(user);
		}
		result.setDesc(ConstantsMark.INFO_UPDATESUCCESS);
		return result;
	}
	
	@RequestMapping(value = "/shoppingbefore",method = RequestMethod.GET)
	public ModelAndView shoppingbefore(HttpServletRequest request,HttpServletResponse response,Integer id){
		ModelAndView result = new ModelAndView();
		Product product = new Product();
		List<Product> productList = productService.selectAll(product);
		result.addObject("productList", productList);
		result.addObject("memberid", id);
		result.setViewName("/pages/member/shopping");
		return result;
	}
	
	@RequestMapping(value = "/shopping",method = RequestMethod.POST)
	@ResponseBody
	public Result shopping(HttpServletRequest request,HttpServletResponse response,Integer memberid,Integer productid){
		Result result = new Result();
		MemberUtil.addSaleOrder(memberid,productid, memberService, orderService, productService, ordermiService, sysManagerService);
		result.setDesc(ConstantsMark.INFO_UPDATESUCCESS);
		return result;
	}
	
	@RequestMapping(value = "/homepage")
	public ModelAndView homepage(HttpServletRequest request
			) throws ParseException{
		ModelAndView result = new ModelAndView();
		int sysuserid = (int)request.getSession().getAttribute(CommonInstans.LOGINUSERID);
		TSysuser user = sysManagerService.selectByPrimaryKey(sysuserid);
		if(user !=null && user.getMemberid()!=null){
			Member member = memberService.selectByPrimaryId(user.getMemberid());
			if(member!=null){
				Integer hasamount = withdrawService.gethasamount(member.getId());
				member.setHasamount(hasamount);
			}
			result.addObject("member", member);
		}
		result.setViewName("/pages/member/homepage");
		return result;
	}
	
	@RequestMapping(value = "/homepage1")
	public ModelAndView homepage1(HttpServletRequest request,Integer memberid) throws ParseException{
		ModelAndView result = new ModelAndView();
		int sysuserid = (int)request.getSession().getAttribute(CommonInstans.LOGINUSERID);
		TSysuser user = sysManagerService.selectByPrimaryKey(sysuserid);
		Member member = memberService.selectByPrimaryId(memberid);
		if(member!=null){
			Integer hasamount = withdrawService.gethasamount(member.getId());
			member.setHasamount(hasamount);
		}
		result.addObject("user", user);
		result.addObject("member", member);
		result.setViewName("/pages/member/homepage1");
		return result;
	}
	
	
	@RequestMapping(value = "/showStream")
	public ModelAndView showStream(HttpServletRequest request,Member member
			) throws ParseException{
		ModelAndView result = new ModelAndView();
		member.setDisabled(1);
		List<Member> memberList = memberService.getMembernum(member);
		result.addObject("member", member);
		result.addObject("memberList", memberList);
		List<MemberVo> ob = memberService.forMatterTx(memberList);
		JSONArray obj = JSONArray.fromObject(ob);
		result.addObject("data", obj);
		result.setViewName("/pages/member/stream");
		return result;
	}
}
